package com.sc.test.socketDemo.serverClient.shoutDownDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @version 1.0
 * @Author: 许啸林 使用 Socket 对象创建一个客户端连接 向本机 9999端口发送 hello,wold
 * @Date: 2021/6/6 15:17
 */
public class ClientDemo2 {
    /**
     *  思路
     *  1. 连接服务端 new Socket(InetAdderss, ip)
     *  2. 连接后生成socket 通过输出字节流流写入 hello,world 到数据通道
     *  3. 关闭io,连接
     *  4. 接收服务端返回的 hello,client
     * @param args
     * @throws UnknownHostException
     */
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        OutputStream outputStream = socket.getOutputStream();
        String sendInfo = "hello,world";
        outputStream.write(sendInfo.getBytes());
        // 停止输出
        socket.shutdownOutput();
        System.out.println("向服务端发送信息:" + sendInfo);
        InputStream inputStream = socket.getInputStream();
        byte[] readData = new byte[1024];
        int index = 0;
        System.out.println("获取服务端字节流信息: ");
        while ((index = inputStream.read(readData)) != -1) {
            System.out.println(new String(readData, 0, index));
        }

        outputStream.close();
        socket.close();
    }
}
